#!/usr/bin/env bash

set -e
source $(dirname $0)/scripts/readlinkdashf.sh

BASEDIR=$(readlinkdashf $(dirname $0))
BINDIR=${BASEDIR}/bin

if [ $PWD != $BASEDIR ]; then
	cd $BASEDIR
fi

ORG_PATH="github.com/sorintlab"
REPO_PATH="${ORG_PATH}/stolon"

mkdir -p ${BINDIR}

VERSION=${STOLON_VERSION:-$(${BASEDIR}/scripts/git-version.sh)}
LD_FLAGS="-s -X ${REPO_PATH}/cmd.Version=$VERSION"

# for static compilation we need to compile with cgo disabled (CGO_ENABLED=0),
# this will trigger a rebuild of all the packages and also the go std library
# (using a different install suffix called `cgo`, will use this since it's the
# name used by many projects but IMHO it's misleading...).
# If the user has write access to the go distribution pkg dir we can use "go
# install". If not possible we have to use `go build` which is slower since
# it'll rebuild every needed package everytime.

use_go_install=

go_root_dir=$(go env GOROOT)
go_host_os=$(go env GOHOSTOS)
go_host_arch=$(go env GOHOSTARCH)
cgodisabled_pkg_dir=${go_root_dir}/pkg/${go_host_os}_${go_host_arch}_cgo

if [ -e ${cgodisabled_pkg_dir} ]; then
	use_go_install=1
fi

if [ -w ${go_root_dir}/pkg ]; then
	use_go_install=1
fi

for cmd in sentinel proxy; do
	CGO_ENABLED=0 go build -installsuffix cgo -ldflags "$LD_FLAGS" -o ${BINDIR}/stolon-${cmd} ${REPO_PATH}/cmd/${cmd}
done
CGO_ENABLED=0 go build -installsuffix cgo -ldflags "$LD_FLAGS" -o ${BINDIR}/stolonctl ${REPO_PATH}/cmd/stolonctl

go build -ldflags "$LD_FLAGS" -o ${BINDIR}/stolon-keeper ${REPO_PATH}/cmd/keeper 

# Copy binaries to Dockerfile image directories
declare -a DOCKERFILE_PATHS
DOCKERFILE_PATHS=(${BASEDIR}/examples/kubernetes/image/docker)
for path in "${DOCKERFILE_PATHS[@]}"
do
  rm -rf $path/bin/
  mkdir -p $path/bin/
  for cmd in stolon-keeper stolon-sentinel stolon-proxy stolonctl; do
          cp ${BINDIR}/${cmd} $path/bin/
  done
done
